<?php 

use Swoole\Http\Client as WebSocketClient;

class Client
{
	protected $protocol;

	protected $host;

	protected $port;

	protected $query;

	protected $client;

	protected $allow_events = ['onOpen', 'onMessage', 'onClose'];

	public function __construct($url)
	{
		$data = parse_url($url);

		$this->protocol = $data['scheme'];
		$this->host = $data['host'];
		$this->port = $data['port'];
		$this->query = $data['query'];

		if ($this->protocol == 'wss') {
			echo 'unsupport protocol';
		}

		$this->client = new WebSocketClient($this->host, $this->port);
	}

	public function start(Callable $callback)
	{
		$this->client->upgrade('/?' . $this->query, $callback);
	}

	public function __set($field, $value)
	{
		if (in_array($field, $this->allow_events) && is_callable($value)) {
			$this->client->on(strtolower(substr($field, 2)), $value);
		} else {
			echo 'Unsupport Event';
		}		
	}

	public function __call($method, $params)
	{
		return $this->client->{$method}(...$params);
	}
}

